package com.iap.admin.mediator
{
	import com.iap.admin.event.VectorEvent;
	import com.iap.admin.signal.VectorRequestSignal;
	import com.iap.admin.view.AdminMenuView;
	import com.iap.admin.view.VectorView;
	import com.iap.admin.view.vector.VectorEditView;
	import com.iap.app.AppGlobal;
	import com.iap.app.data.AppData;
	import com.iap.common.model.VectorModel;
	
	import mx.collections.ArrayList;
	
	import spark.components.Group;
	import spark.events.GridEvent;
	import com.iap.common.mediator.BaseMediator;

	public class VectorMediator extends BaseMediator
	{
		[Inject]
		public var view:VectorView;
		[Inject]
		public var request:VectorRequestSignal;
		
		private var createMode:Boolean = false;
		
		override public function onRegister():void
		{
			view.onOptionClick.add(onClick);
			addContextListener(VectorEvent.RESPONSE, responseHandler);
			addViewListener(GridEvent.GRID_CLICK, gridClickEvent);
			dispatchRequest();
		}
		
		private function gridClickEvent(evt:GridEvent):void
		{ 
			var item:VectorModel = evt.item as VectorModel;
			if(item==null) return;
			edit(item);
		}
		
		private function dispatchRequest():void
		{
			AppGlobal.startWait();
			request.dispatch(new VectorModel(), VectorRequestSignal.GET);
		}
		
		private function responseHandler(evt:VectorEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.task == VectorRequestSignal.SAVE && createMode)
			{
				edit(evt.response.result as VectorModel);
				createMode = false;
			} else {
				view.datagrid.dataProvider = new ArrayList(evt.response.result as Array);
			}
		}
		
		private function onClick(itemName:String):void
		{
			switch(itemName)
			{
				case VectorView.HOME_NAME:
				{
					optionHome();
					break;
				}
				case VectorView.CREATE_NAME:
				{
					create();
					break;
				}
			}
		}
		
		private function optionHome():void
		{
			setView(view.parent as Group, new AdminMenuView(), BaseMediator.FX_GLIDE_OUT);
		}
		
		private function create():void
		{
			AppGlobal.startWait();
			createMode = true;
			var empty:VectorModel = new VectorModel();
			empty.name = "";
			empty.vectorImages = [];
			empty.vectorTags = [];
			request.dispatch(empty, VectorRequestSignal.SAVE);
		}
		
		private function edit(item:VectorModel):void
		{
			var newView:VectorEditView = new VectorEditView();
			newView.onReady.addOnce(function(str:String):void{
				newView.fill(item);
			});
			setView(view.parent as Group, newView);
		}
	}
}